import { Form, class_esy, Select, isArray, Input, Button, cityList, Toast } from 'esy-ui';
import { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { Header } from '@/components';
import { useFormatText } from '@/hooks';
import { form_ipt_com_1, form_iptarea_com, form_slt_com } from '@/styles/esy-ui';
import { postAddBindBank, postAddBindWallet, postPlatBank } from '@/services';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import Bank1Icon from '@/components/icon/Bank1';
import ProvinceIcon from '@/components/icon/Province';
import CountyIcon from '@/components/icon/County';
import BankIcon from '@/components/icon/Bank';
import TRC20Icon from '@/components/icon/TRC20';
import AddrIcon from '@/components/icon/Addr';

const FormItem = Form.Item;

// 选择类型
const types = [
  {
    tKey: 'text_71',
    id: 2,
  },
  {
    tKey: 'text_72',
    id: 3,
  },
];

const usdTypes = [
  {
    text: 'USDT-TRC20',
    value: 229,
  },
  // {
  //   text: 'text_71',
  //   value: 2,
  // },
];

function AddBand() {
  const { text } = useFormatText();
  const { userInfo } = useUserInfoStore();
  const { changeState } = useGlobalStore();
  // 新增银行/钱包切换
  const [type, setType] = useState(types[0].id);
  // 可选银行列表
  const [banks, setBanks] = useState([]);
  // 县城
  const [citys, setCitys] = useState([]);

  const [form] = Form.useForm();

  // 获取平台支持的银行卡列表
  useEffect(() => {
    if (userInfo?.Token) {
      postPlatBank({ PWType: 0 })
        .then((res: any) => {
          if (isArray(res?.Data)) {
            setBanks(res?.Data.map((it) => ({ ...it, value: it.Id, label: <div>{it.BankName}</div> })));
          }
        })
        .catch(() => {});
    }
  }, [userInfo?.Token]);

  // 新增银行/钱包
  const onSubmit = () => {
    changeState('isLoading', true);
    form
      .validate()
      .then((values) => {
        if (Object.values(values).some((it) => !it)) {
          Toast.show({ content: text('text_88') });
          changeState('isLoading', false);
        } else {
          const api = type === 2 ? postAddBindBank : postAddBindWallet;
          api(values)
            .then(() => {
              Toast.show({ content: text('text_215') });
            })
            .catch(() => {})
            .finally(() => {
              changeState('isLoading', false);
            });
        }
      })
      .catch((err) => {
        console.info(err);
        changeState('isLoading', false);
      });
  };

  return (
    <div className='w-full h-full bg-white flex flex-col'>
      <Header title='text_214' isGoHome />
      <div className='p-4 text-base text-desc flex flex-col justify-between bg-white rounded-lg'>
        <div className='flex justify-center items-center gap-x-3 py-3'>
          {types.map((it) => (
            <button
              key={it.id}
              type='button'
              className={class_esy([
                'flex items-center px-6 py-2 rounded gap-x-2 border border-solid ',
                type === it.id ? 'border-color-21 text-white bg-color-21' : 'bg-color-24 border-color-24 text-desc',
              ])}
              onClick={() => {
                setType(it.id);
              }}
            >
              {text(it.tKey)}
            </button>
          ))}
        </div>
        <div className='mt-1 truncate'>
          {text('text_55')}：{userInfo.Name || '--'}
        </div>
        <Form key={type} form={form} className='flex-1 my-4 text-base'>
          {/* 新增银行卡 */}
          {type === 2 ? (
            <>
              <FormItem className='mb-5' name='BankID'>
                <Select placeholder={text('text_82')} classNames={form_slt_com} options={banks} prefix={<Bank1Icon className='absolute left-3 top-3' />} />
              </FormItem>
              <FormItem className='mb-5' name='SubBankName'>
                <Input placeholder={text('text_83')} classNames={form_ipt_com_1} prefix={<Bank1Icon className='absolute left-3 top-3' />} />
              </FormItem>
              <FormItem className='mb-5' name='Province'>
                <Select
                  placeholder={text('text_84')}
                  classNames={form_slt_com}
                  options={cityList.map((it) => ({ ...it, value: `${it.key}-${it.text}` }))}
                  onSelect={(v) => {
                    form.setFieldValue('County', '');
                    const arr = cityList.find((its) => its.text === v.text)?.children || [];
                    setCitys(arr.map((its) => ({ ...its, value: `${its.key}-${its.text}` })));
                  }}
                  prefix={<ProvinceIcon className='absolute left-3 top-3' />}
                />
              </FormItem>
              <FormItem className='mb-5' name='County'>
                <Select
                  placeholder={text('text_85')}
                  classNames={{
                    ...form_slt_com,
                    'dropdown:expand': 'max-h-48 shadow-md',
                    options: 'max-h-48 transition-transform transition-opacity duration-200 overflow-x-hidden overflow-y-auto bg-bg-5 text-text-20',
                  }}
                  options={citys}
                  prefix={<CountyIcon className='absolute left-3 top-3' />}
                />
              </FormItem>
              <FormItem className='mb-5' name='AccountNo'>
                <Input placeholder={text('text_86')} classNames={form_ipt_com_1} prefix={<BankIcon className='absolute left-3 top-3' />} />
              </FormItem>
            </>
          ) : (
            <>
              <FormItem className='mb-5' name='BankID'>
                <Select placeholder={text('text_216')} classNames={form_slt_com} options={usdTypes} prefix={<TRC20Icon className='absolute left-3 top-3' />} />
              </FormItem>
              <FormItem className='mb-5' name='AccountNo'>
                <Input placeholder={text('text_87')} classNames={form_ipt_com_1} prefix={<AddrIcon className='absolute left-3 top-3' />} />
              </FormItem>
              <FormItem className='mb-5' name='Remark'>
                <Input type='textarea' placeholder={text('text_90')} classNames={form_iptarea_com} />
              </FormItem>
            </>
          )}
          <Button className='flex-1 mt-6 rounded' htmltype='submit' onClick={onSubmit}>
            {text('text_76')}
          </Button>
        </Form>
      </div>
    </div>
  );
}

export default observer(AddBand);
